<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class PictureController extends Controller
{
  private $photoConf;
  private $logoConf;

  public function __construct(Request $request)
  {
    parent::__construct($request, 'Picture', 'PictureResource');
    $this->photoConf = config('coreapi.photo');
    $this->logoConf = config('coreapi.logo');
  }

  public function store(Request $request)
  {
    Log::debug(__METHOD__);

    $path = $filename = '';
    $params = [];
    $newobj = $newresource = $validator = $file = $response = null;

    $validator = Validator::make($request->all(), $this->model::$insertRules);
    if ($validator->fails()) {
      return response()->json([
        'error' => $validator->errors(),
      ], 400);
    }
    $params = $request->all();
    try {
      if ($file = $request->file('image')) {
        if ($request->type_id == $this->photoConf['type_id']) {
          $path = $this->photoConf['path'];
        }
        if ($request->type_id == $this->logoConf['type_id']) {
          $path = $this->logoConf['path'];
        }
        $filename = base_path($path);
        $params['filename'] = basename($filename);
        $params['original_filename'] = $file->getClientOriginalName();
        $params['mime_type'] = $file->getClientMimeType();
        $params['size'] = $file->getSize();
        $params['active'] = true;
      }
      $newobj = $this->model::create($params);
      // $newobj = $this->model::find($newobj->id);
      $newresource = new $this->resource($newobj);
      $response = response()->json([
        'resource' => $newresource->only([
          'id',
          'title',
          'filename',
          'original_filename',
          'mime_type',
          'size',
          'active',
          'created_at',
          'updated_at',
          'user',
          'type'
        ]),
        'message' => trans('coreapi.resource_created'),
      ], 201);
    } catch (Exception $e) {
      $response = response()->json([
        'error' => $e->getMessage(),
      ], 400);
    }

    return $response;
  }

  public function update(Request $request, $id)
  {
    Log::debug(__METHOD__);

    $updobj = $updresource = $validator = $response = null;
    $qryparams = [];
    $path = $filename = '';

    $qryparams = create_qry_params();
    $updobj = $this->model::where($qryparams)
      ->findOrFail($id);
    if ($request->all()) {
      $validator = Validator::make($request->all(), $this->model::$updatetRules);
      if ($validator->fails()) {
        $response = response()->json(['error' => $validator->errors()], 400);
      } else {
        if ($file = $request->file('image')) {
          Storage::delete($updobj->filename);
          if ($request->type_id == $this->photoConf['type_id']) {
            $path = $this->photoConf['path'];
          }
          if ($request->type_id == $this->logoConf['type_id']) {
            $path = $this->logoConf['path'];
          }
          $filename = $file->store($path);
          $updobj->filename = basename($filename);
          $updobj->original_filename = $file->getClientOriginalName();
          $updobj->mime_type = $file->getClientMimeType();
          $updobj->size = $file->getSize();
        }
        $updobj->update($request->all());
        $updresource = new $this->resource($updobj);
        $response = response()->json([
          'resource' => $updresource->only([
            'id',
            'title',
            'filename',
            'original_filename',
            'mime_type',
            'size',
            'active',
            'created_at',
            'updated_at',
            'user',
            'type'
          ]),
          'message' => trans('coreapi.resource_updated'),
        ], 200);
      }
    } else {
      $response = response()->json(['message' => trans('coreapi.no_upd_vales')], 400);
    }

    return $response;
  }

  public function destroy($id)
  {
    Log::debug(__METHOD__);

    $fullpath = '';
    $delobj = $response = null;
    $qryparams = [];

    $qryparams = create_qry_params();
    $delobj = $this->model::where($qryparams)
      ->findOrFail($id);
    if ($delobj->type_id == $this->photoConf['type_id']) {
      $fullpath = $this->photoConf['path'];
    }
    if ($delobj->type_id == $this->logoConf['type_id']) {
      $fullpath = $this->logoConf['path'];
    }
    $fullpath = $fullpath . '/' . $delobj->filename;
    Storage::delete($fullpath);
    $delobj->delete();

    return response()->json([
      'message' => trans('coreapi.resource_deleted'),
    ], 200);
  }

  public function download($id)
  {
    Log::debug(__METHOD__);

    $fullpath = '';
    $obj = null;
    $qryparams = [];

    $qryparams = create_qry_params();
    $obj = $this->model::where($qryparams)
      ->findOrFail($id);
    if ($obj->type_id == $this->photoConf['type_id']) {
      $fullpath = $this->photoConf['path'];
    }
    if ($obj->type_id == $this->logoConf['type_id']) {
      $fullpath = $this->logoConf['path'];
    }
    $fullpath = $fullpath . '/' . $obj->filename;

    return Storage::download($fullpath);
  }
}
